package main.java.web.servlet;

import main.java.domain.Task;
import main.java.domain.User;
import main.java.service.TaskService;
import main.java.service.impl.TaskServiceImpl;
import main.java.service.impl.UserServiceImpl;
import main.java.utils.UploadUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/addTaskServlet")
public class AddTaskServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        res.setCharacterEncoding("utf-8");

        // 获取域对象的值
        Map<String, String> map = (Map<String, String>) req.getAttribute("save_task_map");
        String name = map.get("title");
        String endDay = map.get("end_day");
        String endTime = map.get("end_time");
        String textarea = map.get("textarea");
        String path = (String) req.getAttribute("path");

        // 调用TaskService.addTask()
        TaskService service = new TaskServiceImpl();
        boolean flag = service.add(
                name,
                UploadUtils.getFormatTime(),
                endDay + " " + endTime,
                (int) req.getAttribute("id"),
                path
        );

        req.removeAttribute("save_task_map");
        req.removeAttribute("id");
        req.removeAttribute("path");

        if (flag) {
            // 添加成功
            // 更新现有作业列表
            HttpSession session = req.getSession();
            session.removeAttribute("tasks");
            User user = (User)session.getAttribute("user");
            List<Task> tasks = service.findAll(user.getId(), user.getType());
            session.setAttribute("tasks", tasks);

            res.sendRedirect(req.getContextPath()+"/index.jsp");
        } else {
            // 失败
            res.getWriter().write("<script>alert('添加失败')</script>");
        }
    }
}
